#include <iostream>
#include <cstdio>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>

void sig_handler(int signo)
{
    std::cout << "pthread id in the sighanler:" << pthread_self() << std::endl;
    if (signo == SIGALRM)
    {
        std::cout << "timeout....." << std::endl;
    }
    alarm(2);
}
 
void *func(void *arg)
{
    if (signal(SIGALRM, sig_handler) == SIG_ERR)
    {
        perror("signal sigalarm error");
        exit(1);
    }
    //在子线程中设置定时器
    alarm(2);
    int i;
    for (i = 1; i <= 100; i++)
    {

        std::cout << "thread id:" << pthread_self() << std::endl;
        sleep(1);
    }

    return (void *)arg;
}

int main()
{
    int err;
    pthread_t t1;

    //设置线程分离属性
    pthread_attr_t attr;
    pthread_attr_init(&attr);

    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

    if ((err = pthread_create(&t1, NULL, func, NULL)) < 0)
    {
        perror("pthread_create");
        exit(1);
    }

    //信号集
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set,SIGALRM);
    pthread_sigmask(SIG_SETMASK,&set,NULL);
    


    while (1)
    {
        std::cout << "thread id" << pthread_self() << std::endl;

        sleep(10);
    }

    std::cout << "control thread over" << std::endl;

    return 0;
}